let laypage = layui.laypage
let form = layui.form

let page = {
  pagenum: 1,
  pagesize: 2
}

getuser()

form.verify({
  pwd: [/^\S{6,12}$/, '密码不能出现空格且长度为6~12位'],
  repeatpwd: function (value, item) {
    let pw = $(item).parent().parent().prev().find('input').val()
    if (value !== pw) {
      return '两次密码不一致!'
    }
  }
})

function getuser() {
  $.ajax({
    url: 'admin/users',
    data: page,
    success: function (res) {
      if (res.status === 1) {
        return layer.msg(res.message);
      }
      let html = template('tr', res);
      $('tbody').html(html);
      readpage(res.total)
    }
  })
}

function readpage(res) {
  layui.use('laypage', function(){
    //执行一个laypage实例
    laypage.render({
      elem: 'demo', //注意，这里的 test1 是 ID，不用加 # 号
      count: res, //数据总数，从服务端得到
      limit: page.pagesize,
      limits: [2, 3, 5, 10],
      curr: page.pagenum,
      layout: ['prev', 'page', 'next', 'skip', 'count', 'limit'],
      jump: function (obj, first) {
        if(!first){
          page.pagesize = obj.limit;
          page.pagenum = obj.curr;
          getuser()
        }
      }
    });
  });
};

// 删除
$('tbody').on('click', '.dele', function (ev) {
  ev.preventDefault();
  let id = $(this).data('id');
  layer.confirm('确认要删除用户吗？', {icon: 3, title:'提示'}, function(index){
    $.ajax({
      url: 'admin/users/' + id,
      type: 'DELETE',
      success: function (res) {
        if (res.status === 1) {
          return layer.msg('删除用户失败!');
        }
        layer.msg('删除用户成功!');
        getuser();
        layer.close(index);
      }
    });
  });
});

// 重置密码
let Layer_thickness;
$('tbody').on('click', 'button:contains(重置密码)', function (ev) {
  ev.preventDefault();
  let id = $(this).data('id')
  Layer_thickness = layer.open({
    type: 1,
    title: '重置密码',
    skin: 'layui-layer-rim', //加上边框
    area: ['420px', '240px'], //宽高
    content: $('#pw').html(),
    success: function (layero) {
      $(layero).find('input[type=hidden]')[0].value = id
    }
  });
})

$('body').on('submit', '#pwform', function (ev) {
  ev.preventDefault()
  let data = $(this).serialize()
  let id = $('input[type=hidden]').val()
  $.ajax({
    url: 'admin/users/' + id,
    type: 'put',
    data: data,
    success: function (res) {
      if (res.status === 1) return layer.msg('重置密码失败!')
      layer.msg('重置密码成功!');
      layer.close(Layer_thickness);
    }
  })
  
  
})